package jvm;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

/**
 * @Author: admin
 * @Description:
 * @Date: 2018/8/10 14:44
 */

//public class MultiThread {
//    public static void main(String[] args) {
//        // 获取Java线程管理MXBean
//        ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
//        // 不需要获取同步的monitor和synchronizer信息，仅获取线程和线程堆栈信息
//        ThreadInfo[] threadInfos = threadMXBean.dumpAllThreads(false, false);
//        // 遍历线程信息，仅打印线程ID和线程名称信息
//        for (ThreadInfo threadInfo : threadInfos) {
//            System.out.println("[" + threadInfo.getThreadId() + "] " + threadInfo.
//                    getThreadName());
//        }
//    }
//}


public class MultiThread {
    public static void main(String[] args) throws Exception {
        Runner one = new Runner();
        Thread countThread = new Thread(one, "CountThread1");
        countThread.start();
// 睡眠1秒，main线程对CountThread进行中断，使CountThread能够感知中断而结束
        TimeUnit.SECONDS.sleep(1);
        countThread.interrupt();
        Runner two = new Runner();
        countThread = new Thread(two, "CountThread2");
        countThread.start();
// 睡眠1秒，main线程对Runner two进行取消，使CountThread能够感知on为false而结束
        TimeUnit.SECONDS.sleep(1);
        two.cancel();
    }

}

class Runner implements Runnable {
  private long i;
  private volatile boolean on = true;
  @Override
  public void run() {
      while (on && !Thread.currentThread().isInterrupted()){
          i++;
      }
      System.out.println(Thread.currentThread().getName()+ " Count i = " + i);
  }
  public void cancel() {
      System.out.println(Thread.currentThread().getName());
      on = false;
  }
}
